//
//  MainViewController.swift
//  性别检测
//
//  Created by 优裁科技 on 2017/5/15.
//  Copyright © 2017年 优裁科技. All rights reserved.
//

import UIKit
import Photos

let K_APP_WIDTH = UIScreen.main.bounds.size.width
let K_APP_HEIGHT = UIScreen.main.bounds.size.height

//Face++ 图像识别 配置信息
let K_APP_API_KEY = "XObhooobQlwMorIVMLqeyOErisCzW3ta"
let K_APP_API_SECRET = "suWzN-9-IFsdZhGN2HaGmQRWUEqoGFRQ"

/**
 * 性别检测
 */
class MainViewController: UIViewController,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //MARK: - property
    var activity:UIActivityIndicatorView?   //加载进度
    
    
    //MARK: - override func
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = UIColor.white
        
        self.initView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //MARK: - initView
    func initView(){
        //MARK:背景色
        self.view.backgroundColor = UIColor.white
        
        var x = CGFloat.init(0)
        var y = CGFloat.init(0)
        var w = CGFloat.init(0)
        var h = CGFloat.init(0)
        
        //MARK:打开相册或拍照
        x = 20
        w = K_APP_WIDTH - 2 * x
        h = 40
        y = 60
        let btnOpenImge = UIButton.init(frame: .init(x: x, y: y, width: w, height: h))
        btnOpenImge.setTitle("点击选择图片", for: .normal)
        
        btnOpenImge.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btnOpenImge.setTitleColor(.white, for: .normal)
        btnOpenImge.backgroundColor = UIColor.blue
        
        btnOpenImge.addTarget(self, action: #selector(btnChoicePicAction(sender:)), for: .touchUpInside)
        self.view.addSubview(btnOpenImge)
        
        //MRK:加载进度
        activity = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
        activity?.center = self.view.center
        activity?.hidesWhenStopped = true
        self.view.addSubview(activity!)
        self.view.bringSubview(toFront: activity!)
    }
    
    
    //MARK: - 提交检测
    func submitDetection(imgData:Data){
        
        activity?.startAnimating()
        
        let paramaters = [
            "api_key":K_APP_API_KEY,
            "api_secret":K_APP_API_SECRET,
            "image_base64":imgData.base64EncodedString(),
            "return_attributes":"gender,cloth_color"
        ]
        
        let strUrl = "https://api-cn.faceplusplus.com/humanbodypp/beta/detect"
        let operationManager = AFHTTPRequestOperationManager.init()
        operationManager.post(strUrl, parameters: paramaters, success: { (requestOperation:AFHTTPRequestOperation?, responseData:Any?) in
            
            var strMag = "请求失败"
            var isOK = false
            if var dicData = responseData as? [String:AnyObject] {

                if let code = dicData["time_used"] as? Int, code != 3 {
                    strMag = "请求成功"
                    print("请求结果：\(dicData)")
                    
                    if let tempDuc:[[String:AnyObject]] = dicData["humanbodies"] as? [[String : AnyObject]],tempDuc.count > 0 {
                        isOK = true
                        let gender:[String:AnyObject] = (tempDuc.first?["attributes"]?["gender"] as? [String : AnyObject])!
                        
                        DispatchQueue.main.async {
                            alertMessage(strTitle: String.init(format:"%@",gender["value"]! as! CVarArg) == "Male" ? "男生" : "女生")
                            return
                        }
                    }
                }
                else{
                    strMag = (requestOperation?.responseString)!
                    
                    DispatchQueue.main.async {
                        alertMessage(strTitle: strMag)
                    }
                }
            }
            
            DispatchQueue.main.async {
                
                if isOK == false {
                    alertMessage(strTitle: "无法识别")
                }
                
                self.activity?.stopAnimating()
            }

        }) { (requestOperation:AFHTTPRequestOperation?, error:Error?) in
            
            print("识别异常！详见：\(error.debugDescription)")
            
            DispatchQueue.main.async {
                self.activity?.stopAnimating()
                
                alertMessage(strTitle: "图像识别异常！")
            }
        }
    }
    
    
    //MARK: - UIImagePickerControllerDelegate、UINavigationControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //UIImagePickerControllerOriginalImage  原始图像
        //UIImagePickerControllerEditedImage    编辑后的图片(开启编辑该对象才存在)
        
        self.dismiss(animated: true, completion: {
            var img:UIImage? = info[UIImagePickerControllerOriginalImage] as? UIImage
            if picker.isEditing {
                img = info[UIImagePickerControllerEditedImage] as? UIImage
            }
            
            if img != nil {
                let imgData = UIImageJPEGRepresentation(img!, 0.5)!
                
                //提交检测
                self.submitDetection(imgData: imgData)
            }
        })
    }
    
    //取消
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
    
    
    //MARK: - 选择图片
    func btnChoicePicAction(sender:UIButton) {
    
        let actionSheet = UIActionSheet.init(title:nil,
                                             delegate: self as UIActionSheetDelegate,
                                             cancelButtonTitle: "取消",
                                             destructiveButtonTitle:nil,
                                             otherButtonTitles: "从手机相册选择","拍照")
        actionSheet.show(in: self.view)
    }

    
    //MARK: - UIActionSheetDelegate
    func actionSheetCancel(_ actionSheet: UIActionSheet) {
        actionSheet.dismiss(withClickedButtonIndex: 0, animated: true)
    }
    
    func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.allowsEditing = true //允许编辑
        
        //手机相册
        if buttonIndex == 1 {
            
            //相册权限检测
            PHPhotoLibrary.requestAuthorization({ (status:PHAuthorizationStatus) in
                if status != PHAuthorizationStatus.authorized {
                    
                    DispatchQueue.main.async {
                        print("请先开启相册访问权限")
                        
                        self.openSetting()
                    }
                }
                else{
                    //相册
                    imagePickerController.sourceType = .photoLibrary
                    
                    self.present(imagePickerController, animated: true, completion: nil)
                }
            })
        }
        //拍照
        else if buttonIndex == 2 {
            
            //相机权限判断
            let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
            if(authStatus == .denied || authStatus == .restricted) {
                
                print("请先开启相机访问权限")
                self.openSetting()
                
                return
            }
            
            //拍照
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }
    }
    
    //开启设置权限
    func openSetting(){
        let strUR = UIApplicationOpenSettingsURLString
        
        if UIApplication.shared.canOpenURL(URL.init(string: strUR)!) {
            UIApplication.shared.openURL(URL.init(string: strUR)!)
        }
    }
    

}
